package com.rhino.security.filter;


import com.rhino.security.constants.SecurityConstants;
import com.rhino.security.properties.SecurityProperties;
import com.rhino.security.service.RefreshJWTTokenService;
import com.rhino.security.utils.JwtTokenUtil;
import com.rhino.security.vo.JWTTokenVO;
import com.rhino.security.vo.JwtUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Jwt超时刷新令牌类，包括（前端，后端）。
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    RefreshJWTTokenService refreshJWTTokenService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        String token = request.getHeader(SecurityConstants.JWT_HEADER);

        if (StringUtils.isBlank(token)) {
            chain.doFilter(request, response);
            return;
        }

        Claims claimsFromToken = null;
        try {
            claimsFromToken = jwtTokenUtil.getClaimsFromToken(token);
        } catch (Exception exception) {
            // 针对token过期的异常进行处理。
            if (exception instanceof ExpiredJwtException) {
                // 前端刷新token
                if (securityProperties.getJwt().getFrontWeb()) {
                    request.setAttribute(SecurityConstants.EXPIRED_JWT_EXCEPTION, true);
                } else {
                    // 后端主动刷新token
                    String userName = ((ExpiredJwtException) exception).getClaims().getSubject();
                    JWTTokenVO jwtTokenVO = refreshJWTTokenService.getTokenByUserName(userName);
                    request.setAttribute(SecurityConstants.INITIATIVE_JWT_TOKEN, jwtTokenVO);
                    claimsFromToken = jwtTokenUtil.getClaimsFromToken(jwtTokenVO.getAccessToken());
                }
            }
        }

        if (claimsFromToken != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            String username = claimsFromToken.getSubject();
            String name = claimsFromToken.get("name", String.class);
            if (username != null && jwtTokenUtil.validateToken(claimsFromToken)) {

                List<GrantedAuthority> authorities = jwtTokenUtil.getAuthorities(claimsFromToken);
                UserDetails userDetails = new JwtUser(username, username, name, authorities);

                // 将用户信息存入 authentication，方便后续校验
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                // 将 authentication 存入 ThreadLocal，方便后续获取用户信息
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        chain.doFilter(request, response);
    }


}
